// Widgets/Protocol/ProtocolIdCardAddress/ProtocolIdCardAddress.js
var QQMapWX = require('../../../common/qqmap-wx-jssdk.min.js');
var qqmapsdk;
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    borrowUserAddress: {
      type: String,
    }, // 借款人地址
    borrowUserIdCardFrontImgUrl: {
      type: String,
    }, // 借款人身份证正面照
    borrowUserIdCardBackImgUrl: {
      type: String,
    }, // 借款人身份证反面
    iouContent: {
      type: String, // 出借人证件照
    },
    iouContentList: {
      type: Array,
    }
  },
  options: {
    styleIsolation: 'shared',
  },
  lifetimes: {
    attached: function() {
      qqmapsdk = new QQMapWX({
        key: 'MEZBZ-6D3O4-JPJU6-XRZRL-LH73V-PYFUZ'
      });
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    uploadFileUrl: app.globalData.global.uploadFileUrl,
    brandId: app.globalData.global.brandId,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    selAddress(){
      var _this = this;
      wx.getSetting({
        success: (res) => {
          console.log(res,'res')
          if(res.authSetting['scope.userFuzzyLocation']){
            _this._getFuzzy();
          }else{
            wx.authorize({
              scope: 'scope.userFuzzyLocation',
              success: ()=>{
                _this._getFuzzy();
              },
              fail: (err) => {
                console.log(err,'err')
                wx.showModal({
                  title: '获取定位信息',
                  content: '请允许获取您的位置信息，否则小程序部分功能将无法使用',
                  success: (res) => {
                    if(res.confirm){
                      wx.openSetting({
                        success: (res) => {
                          if(res.authSetting['scope.userFuzzyLocation']){
                            _this._getFuzzy();
                          }
                        },
                      })
                    }
                  }
                })
              }
            })
          }
        },
        fail: function(err){
          console.log(err,'err')
        }
      })
    },
    // 选择地图定位
    _getFuzzy(){
      console.log('定位')
      let _this = this;
      wx.getFuzzyLocation({
        type: 'gcj02',
        success: (res) => {
          console.log(res,'位置信息')
          const latitude = res.latitude
          const longitude = res.longitude
          wx.chooseLocation({
            latitude,
            longitude,
            success: (res)=> {
              console.log(res,'res')
              qqmapsdk.reverseGeocoder({
                location: {
                  'latitude': res.latitude,
                  'longitude': res.longitude
                },
                success: (res)=> {
                  var res = res.result;
                  console.log(res,'解析地址')
                  var detailedAddress = res.address_component.street_number ? res.address_component.street + res.address_component.street_number : res.formatted_addresses.recommend ? res.formatted_addresses.recommend : res.address_component.street;
                  var provinceCity = `${res.address_component.province}/${res.address_component.city}/${res.address_component.district}`;
                  _this.triggerEvent('updateValue',{'data': `${provinceCity} ${detailedAddress}`,'name': 'borrowUserAddress'})
                },
                fail: (err)=> {
                  console.log(err,'解析错误')
                }
              })
            }
          })
        },
        fail: (err) => {
          console.log(err,'err')
        }  
      })
    },
    // 选择照片
    selImg(e){
      let _this = this;
      let type = e.target.dataset.type||e.currentTarget.dataset.type;
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        success(e){
          console.log(e.tempFiles)
          var token = wx.getStorageSync('access_token');
          var timeStamp = new Date().getTime();
          wx.uploadFile({
            url: _this.data.uploadFileUrl, // 上传接口
            filePath: e.tempFiles[0].tempFilePath,
            name: 'file',
            formData: { 'brandId': _this.data.brandId ,'access_token': token,'timeStamp': timeStamp},
            success(res) {
              console.log(res,'res')
              var res = JSON.parse(res.data);
              if(res.success){
                if(type == '1'){
                  if(_this.properties.borrowUserIdCardFrontImgUrl == ''){
                    _this.triggerEvent('updateValue',{'data': res.data,'name': 'borrowUserIdCardFrontImgUrl'})
                  }else{
                    _this.triggerEvent('updateValue',{'data': res.data,'name': 'borrowUserIdCardBackImgUrl'})
                  }
                }else{
                  _this.triggerEvent('updateImgList',{'data': res.data,'name': 'iouContentList'})
                }
              }else{
                wx.showToast({
                  title: res.errMessage,
                  icon: 'none',
                })
              }
            },
          });
        },
        fail: function(err){
          console.log(err,'err')
        }
      })
    },
    // 删除图片
    delImg(e){
      let _this = this;
      let name = e.target.dataset.name||e.currentTarget.dataset.name;
      _this.triggerEvent('updateValue',{'data': '','name': name})
    },
    delListImg(e){
      let _this = this;
      let name = e.target.dataset.name||e.currentTarget.dataset.name;
      let index = e.target.dataset.index||e.currentTarget.dataset.index;
      _this.triggerEvent('updateImgList',{'data': '','name': name,'index': index})
    }
  }
})